<template>
	<!-- 巡检计划整改点位(列表) -->
	<view class="check-assets">
		<uni-card title="2022日常安全巡检">
			<template v-slot:title>
				<view class="card-title">
					<view>
						<text>{{ lastData.inspPlanName }}</text>
					</view>
					<text class="right-txt color1">{{
            lastData.inspRecordStatusCn
          }}</text>
					<!-- <text class="right-txt color2">已结束</text> -->
				</view>
			</template>
			<uni-list :border="false">
				<uni-list-item>
					<template v-slot:body>
						<view class="slot-box" style="width: 100%">
							<view>
								<uni-icons type="shop-filled" size="18" color="#198a6c"></uni-icons>
								<text>{{ lastData.storeName }}</text>
							</view>
							<view class="check-name">
								<uni-icons type="calendar" size="14"></uni-icons>{{ lastData.inspPlanStartTime }} 至
								{{ lastData.inspPlanEndTime }}
							</view>
							<view class="check-name">
								<uni-icons type="compose" size="14"></uni-icons>{{ lastData.inspPlanRemarks ||'--'}}
							</view>
							<view class="check-name">
								计划巡检时间：{{ lastData.addTime?.replace('T',' ') }}
							</view>
							<view style="display: flex; justify-content: space-between">
								<text>总巡检项：{{ lastData.inspItemQty + "" }}</text>
								<text>合格项：{{ lastData.inspItemOkQty + "" }}</text>
								<view>
									不合格项：<text style="color: #f00">{{
                    lastData.inspItemNgQty + ""
                  }}</text>
								</view>
							</view>
						</view>
					</template>
				</uni-list-item>
			</uni-list>
		</uni-card>

		<view class="content">
			<uni-card>
				<template v-slot:title>
					<view class="card-title">
						<view>
							<uni-icons type="location-filled" size="18" color="#198a6c"></uni-icons>
							<text>巡检点位：{{ inspPositionName }}</text>
						</view>
						<!-- <text class="right-txt color1">进行中</text> -->
						<!-- <text class="right-txt color2">已结束</text> -->
					</view>
				</template>
				<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData">
					<uni-forms-item :required="showType!=='see'" disable name="name" v-for="(item, index) in selOps"
						:key="index" :label="item.inspContentDtlName" class="remarks">
						<uni-data-checkbox :selectedColor="item.inspResult==1?'red':''" v-model="item.inspResult"
							:localdata="sexs" :disabled="showType == 'see'" class="items" />
					</uni-forms-item>

					<uni-forms-item label="巡检备注:" name="execuRemarks" class="remarks">
						<uni-easyinput type="textarea" v-model="valiFormData.execuRemarks"
							:placeholder="showType == 'see'?' ':'请输入巡检备注描述'" :disabled="showType == 'see'" />
					</uni-forms-item>
					<uni-forms-item label="已有图片:" class="remarks" v-if="imageValue.length>0">
						<view class="havaImg">
							<view class="imgs" v-for="(item, index) in imageValue" :key="index">
								<image :src="item.url" mode="aspectFill" class="viewImg" @click="previewImage(item.url)"></image>
								<uni-icons type="trash-filled" size="24" v-if="showType != 'see'" style="
                    position: absolute;
                    top: 10rpx;
                    right: 10rpx;
                    background-color: aliceblue;
                    opacity: 0.8;
                  " @click="delImg(index)" color="#333"></uni-icons>
							</view>
						</view>
					</uni-forms-item>

					<uni-forms-item label="上传图片:" class="remarks" v-if="showType != 'see'">
						<uni-file-picker file-mediatype="image" ref="files" :auto-upload="false" mode="grid"
							:limit="lim" @select="select" @delete="deleteFile" title="最多存在9张图片" />
					</uni-forms-item>
				</uni-forms>
			</uni-card>
			<uni-card v-show="inspRectifyFlag">
				<view
					style="text-align: center;margin-bottom: 10px;font-weight: bold;border-bottom: 1px solid #efefef;padding-bottom: 10px;">
					整改信息记录
				</view>
				<!-- 整改信息查看 -->
				<uni-forms-item label="已整改备注:" class="remarks">
					<uni-easyinput type="textarea" v-model="inspRectify.rectifyRemarks" placeholder=" "
						:disabled="true" />
				</uni-forms-item>
				<uni-forms-item label="整改确认备注:" class="remarks">
					<uni-easyinput type="textarea" v-model="inspRectify.rectifyConfirmRemarks" placeholder=" "
						:disabled="true" />
				</uni-forms-item>
				<uni-forms-item label="整改图片:" class="remarks" v-if="imageValue2.length>0">
					<view class="havaImg" >
						<view class="imgs" v-for="(item, index) in imageValue2" :key="index">
							<image :src="item.url" mode="aspectFill" class="viewImg" @click="previewImage(item.url)"></image>
						</view>
					</view>
				</uni-forms-item>
			</uni-card>
		</view>
	</view>
	<view :class="{'bottom-btn':true,'permission-none':isPermission('INSP_RECORD_SFR')}">
		<button class="start-button" @click="submit" v-if="showType != 'see'">
			保存
		</button>
	</view>
	<MessageTip ref="messageTip" :tipContent="'确认删除吗？'" @clickType="handleShowOrHideTip" />
</template>

<script lang="ts" setup>
	import {
		ref,
		reactive,
		computed
	} from "vue";
	import {
		onPullDownRefresh,
		onReachBottom,
		onLoad,
		onBackPress
	} from "@dcloudio/uni-app";
	import {
		subRes,
		contentDtls,
		getMainInfo,
	} from "@/common/api/inspectionAPI.ts";
	import {
		batchUpload
	} from "@/common/util/request.ts"; //上传文件接口
	import {
		imgURL,
		IMGVIEW
	} from "@/common/config/config.ts";
	import {
		isPermission
	} from '@/common/util/common.ts'

	const lastData = ref({}); // 传过来的总数据
	const imgPath = ref([]); // 文件列表
	const valiFormData = ref({
		execuRemarks: null,
	}); // 表单列表
	const selOps = reactive([]); // 明细列表
	const resultArr = reactive([]); // 选择结果
	const inspPositionId = ref();
	const version = ref();
	const thisInfo = ref();

	const imageValue = ref([]);
	const imageValue2 = ref([]);

	const showType = ref("");
	const inspPositionName = ref("");
	const inspRectify = ref({})
	const inspRectifyFlag = ref(false)
	const inspRecordId = ref('')
	const messageTip = ref()
	// const pages = getCurrentPages()
	// pages.forEach(item=>{
	// 	console.log('--------',item.route)
	// })

	onLoad((par) => {
		if (par.showType) {
			showType.value = par.showType;
		}
		inspRecordId.value = par.inspRecordId
		inspPositionId.value = par.inspPositionId;
		// 头部卡片数据
		getMainInfo(par.inspRecordId).then((value) => {
			lastData.value = value.data;
			version.value = value.data.version;
		});
		if (!isPermission('INSP_RECORD_DTL_QUERY')) {
			contentDtls(par.inspRecordId, par.inspPositionId, 0).then((value) => {
				thisInfo.value = value.data;
				inspPositionName.value = value.data.inspRecordDtl.inspPositionName;
				value.data.contentDtls.forEach((item) => {
					selOps.push(item);
				});
				if (value.data.inspRecordDtl) {
					valiFormData.value.execuRemarks = value.data.inspRecordDtl.execuRemarks;
				}
				if (value.data.inspRectify) {
					inspRectify.value = value.data.inspRectify
					inspRectifyFlag.value = true
				}
				// console.log('--------', inspRectify.value);
				// 附件拿来显示
				try {
					value.data.inspRecordDtl.encls.forEach((item) => {
						imageValue.value.push({
							url: IMGVIEW + item.enclUrl,
							extname: "png",
							name: item.enclName,
							enclId: item.enclId,
						});
					});
					value.data.inspRectify.encls.forEach((item) => {
						imageValue2.value.push({
							url: IMGVIEW + item.enclUrl,
							extname: "png",
							name: item.enclName,
							enclId: item.enclId,
						});
					});
				} catch (error) {
					console.log("没有附件");
				}
			});
		}

	});

	// 选择文件
	const select = (res) => {
		imgPath.value = imgPath.value.concat(res.tempFilePaths);
	};

	// 删除文件
	const deleteFile = (res) => {
		imgPath.value.forEach((em: any, i: Number) => {
			if (em == res.tempFilePath) {
				imgPath.value.splice(i, 1);
			}
		});
	};

	// 删除图片
	const yesDel = ref([]);

	const delImg = (index) => {
		messageTip.value.openTip()
		// uni.showModal({
		// 	content: "确认删除吗?",
		// 	success: function(res) {
		// 		if (res.confirm) {
		// 			imageValue.value[index].operType = 1;
		// 			yesDel.value.push(imageValue.value[index]);
		// 			imageValue.value.splice(index, 1);
		// 		}
		// 	},
		// });
	};
	const handleShowOrHideTip = (type: string) => {
		if (type == 'yes') {
			imageValue.value[index].operType = 1;
			yesDel.value.push(imageValue.value[index]);
			imageValue.value.splice(index, 1);
		}
	}
	const lim = computed(() => {
		return 9 - imageValue.value.length + "";
	});

	const rules = [];
	// 单选数据源
	const sexs = [{
			text: "合格",
			value: 0,
		},
		{
			text: "不合格",
			value: 1,
		},
		{
			text: "忽略",
			value: 2,
		},
	];

	const submit = async () => {
		let sysEnclRequestList = []; //附件列表
		if (imgPath.value.length > 0) {
			console.log(imgPath.value);
			await batchUpload(imgPath.value).then((res: any) => {
				let resData = JSON.parse(res);
				console.log(resData);
				if (resData.code == 0) {
					resData.data.forEach((em: any) => {
						sysEnclRequestList.push({
							enclMode: 0,
							enclType: 2, //附件类型 2：图片 3：视频
							enclUrl: em.path,
							operType: 2, //	操作符:0-不变,1-删除,2-新增,3-修改
							enclName: em.originName,
						});
					});
				} else {
					// 上传文件失败！
					uni.showToast({
						title: res.message,
						icon: "none"
					});
				}
			});
		}

		// 提交数据
		let recordContentsArr = []
		selOps.forEach((item, index) => {
			recordContentsArr.push({
				inspPlanContentDtlId: item.inspContentDtlId,
				inspPlanContentId: item.inspContentId,
				inspResult: item.inspResult,
				version: item.version,
				inspRecordContentId: item.inspRecordContentId
			})
		})

		let tosub = false

		selOps.forEach(item => {
			if (item.inspResult == null) {
				uni.showToast({
					title: '请检查必填项！',
					icon: 'none',
				})
			} else {
				tosub = true
			}
		})

		if (!tosub) {
			return
		}

		if (yesDel.value.length != 0) {
			yesDel.value.forEach(item => {
				sysEnclRequestList.push(item)
			})
		}

		const subParams = {
			execuRemarks: lastData.value.execuRemarks,
			inspPlanId: lastData.value.inspPlanId,
			inspRecordId: lastData.value.inspRecordId,
			inspStoreId: lastData.value.inspStoreId,
			version: version.value,
			inspRecordDtls: [{
				execuRemarks: valiFormData.value.execuRemarks,
				inspPlanPositionId: inspPositionId.value,
				encls: sysEnclRequestList,
				recordContents: recordContentsArr,
				inspRecordDtlId: null,
				version: null
			}]
		}

		if (thisInfo.value.inspRecordDtl != null) {
			subParams.inspRecordDtls[0].inspRecordDtlId = thisInfo.value.inspRecordDtl.inspRecordDtlId
			subParams.inspRecordDtls[0].version = thisInfo.value.inspRecordDtl.version
		}
		if (!isPermission('INSP_RECORD_SFR')) {
			subRes(subParams).then(value => {
				if (value.code == 0) {
					uni.showToast({
						title: value.message,
						icon: 'none',
						duration:500
					})
					setTimeout(() => {
						uni.hideToast()
						// uni.navigateTo({
						// 	url:`/pages/ipqc/inspectContent/index?inspRecordId=${inspRecordId.value}&showType=hand`
						// })
						uni.navigateBack({
							delta: 1
						});
					}, 500)

				} else {
					uni.showToast({
						title: value.message,
						icon: 'none'
					})
				}
			})
		}

	};
	const previewImage = (urls: any) => {
		console.log('------------', urls);
		let suffix = urls.split('.')[urls.split('.').length - 1]
		// console.log(suffix);
		let img = ['jpg', 'png', 'webp', 'jpeg']
		if (img.includes(suffix)) {
			// urls = [imgURL + urls]
			console.log(urls);
			uni.previewImage({
				current: 0,
				urls: [urls],
				//长按操作
				longPressActions: {
					itemList: ['发送给朋友', '保存图片', '收藏'],
					success: function(data) {},
					fail: function(err) {}
				}
			})
		} 
	
	}
</script>

<style scoped lang="scss">
	// uni-page-body {
	// 	height: 100%;
	// }

	.check-assets {
		height: 100%;
		padding-bottom: 80px;
		// background-color: #f4f4f4;

		.segmented-control {
			background-color: #fff;
		}
	}

	.content {
		:deep(.uni-list-item__container) {
			padding: 5px 20rpx !important;
		}

		.uni-card:first-child {
			margin-bottom: 5px !important;
		}

		.uni-card:last-child {
			margin-top: 0px !important;
		}
	}

	.card-title {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px;
		border-bottom: 1px solid #ebeef5;
		position: relative;

		.right-txt {
			font-size: 12px;
			color: #fff;
			padding: 5rpx 20rpx;
			box-sizing: border-box;
			border-radius: 18rpx 0 0 18rpx;
			position: absolute;
			right: -20rpx;
		}

		.color1 {
			background-color: #7098ed;
		}

		.color2 {
			background-color: #999999;
		}
	}

	.uni-list-item {
		font-size: 14px !important;

		.check-time {
			color: #fda659;
		}
	}

	.check-name {
		font-size: 12px;
	}

	.footer-btn {
		display: flex;
	}

	.list-btn {
		background-color: #198a6c;
		color: #fff;
		line-height: 2;
		font-size: 14px;
		margin-left: 10rpx;
	}

	.top-text {
		color: #fd8f1a;
	}

	.start-button {
		width: 60%;
		box-sizing: border-box;
		background-color: #fe8f1b;
		line-height: 2;
		color: #fff;
	}

	.change-point {
		border-color: #fe8f1b;
		color: #fe8f1b;
		height: 50rpx;
		line-height: 50rpx;
		box-sizing: border-box;
		font-size: 14px;
		padding: 0rpx 50rpx;
		border-radius: 25rpx;
	}

	:deep(.uni-forms-item__label) {
		flex: 0.8 !important;
		height: auto !important;
	}

	:deep(.uni-forms-item__inner) {
		padding-bottom: 6px !important;
	}

	.remarks {
		:deep(.uni-forms-item__label) {
			flex: 0.45 !important;
		}

		// :deep(.uni-forms-item__label:nth-child(2)){
		// 	flex: 0.4 !important;
		// }
	}

	:deep(.checklist-box) {
		margin: 5px 0 !important;
		margin-right: 10rpx !important;
	}

	.havaImg {
		display: flex;
		flex-flow: row wrap;
	}

	.imgs {
		width: 150rpx;
		height: 150rpx;
		box-sizing: border-box;
		padding: 10rpx;
		position: relative;
	}

	.imgs>image {
		width: 100%;
		height: 100%;
	}

	.imgs>uni-icons {
		position: absolute;
		color: #198a6c;
	}
</style>
